package com.example.mydy;

import android.content.Intent;
import android.content.Context;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.ArrayList;
import java.util.List;

import com.example.mydy.model.Announcement;
import com.example.mydy.utils.MockDataManager;
import com.example.mydy.utils.NetworkUtils;

public class AnnouncementActivity extends AppCompatActivity {
    private static final String TAG = "AnnouncementActivity";
    
    private RecyclerView rvAnnouncements;
    private SwipeRefreshLayout swipeRefreshLayout;
    private FloatingActionButton fabAddAnnouncement;
    private TextView tvNoAnnouncements;
    
    private List<Announcement> announcementList = new ArrayList<>();
    private AnnouncementAdapter announcementAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 设置布局文件，如果有对应的布局文件，例如 activity_announcement.xml
        setContentView(R.layout.activity_announcement);
        
        initViews();
        setupRecyclerView();
        setupListeners();
        
        // 加载数据
        loadAnnouncements();
    }
    
    private void initViews() {
        try {
            rvAnnouncements = findViewById(R.id.rv_announcements);
            swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
            fabAddAnnouncement = findViewById(R.id.fab_add_announcement);
            tvNoAnnouncements = findViewById(R.id.tv_no_announcements);
            
            // 设置返回按钮
            View btnBack = findViewById(R.id.btn_back);
            if (btnBack != null) {
                btnBack.setOnClickListener(v -> {
                    finish(); // 返回上一页
                });
            } else {
                Log.e(TAG, "btn_back not found in layout");
            }
            
            // 设置刷新按钮
            View btnRefresh = findViewById(R.id.btn_refresh);
            if (btnRefresh != null) {
                btnRefresh.setOnClickListener(v -> {
                    loadAnnouncements(); // 刷新公告列表
                });
            } else {
                Log.e(TAG, "btn_refresh not found in layout");
            }
        } catch (Exception e) {
            Log.e(TAG, "Error initializing views", e);
            Toast.makeText(this, "界面初始化错误: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    private void setupRecyclerView() {
        announcementAdapter = new AnnouncementAdapter(this, announcementList);
        rvAnnouncements.setLayoutManager(new LinearLayoutManager(this));
        rvAnnouncements.setAdapter(announcementAdapter);
    }
    
    private void setupListeners() {
        swipeRefreshLayout.setOnRefreshListener(this::loadAnnouncements);
        
        fabAddAnnouncement.setOnClickListener(v -> {
            // 添加新公告
            if (NetworkUtils.isAdmin()) {
                // 显示添加公告对话框
                showAddAnnouncementDialog();
            } else {
                Toast.makeText(this, "仅管理员可以添加公告", Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void loadAnnouncements() {
        swipeRefreshLayout.setRefreshing(true);
        
        // 在离线模式下
        if (NetworkUtils.USE_OFFLINE_MODE) {
            loadMockAnnouncements();
            return;
        }
        
        // TODO: 实现在线模式下加载公告
        // 暂时使用模拟数据
        loadMockAnnouncements();
    }
    
    private void loadMockAnnouncements() {
        // 从MockDataManager获取公告列表
        List<Announcement> announcements = MockDataManager.getInstance().getAllAnnouncements();
        
        // 更新UI
        announcementList.clear();
        announcementList.addAll(announcements);
        announcementAdapter.notifyDataSetChanged();
        
        swipeRefreshLayout.setRefreshing(false);
        
        // 显示或隐藏"暂无公告"提示
        if (announcementList.isEmpty()) {
            tvNoAnnouncements.setVisibility(View.VISIBLE);
        } else {
            tvNoAnnouncements.setVisibility(View.GONE);
        }
        
        Toast.makeText(this, "已加载 " + announcements.size() + " 条公告", Toast.LENGTH_SHORT).show();
    }
    
    private void showAddAnnouncementDialog() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_announcement, null);
        
        final com.google.android.material.textfield.TextInputEditText etTitle = dialogView.findViewById(R.id.et_announcement_title);
        final com.google.android.material.textfield.TextInputEditText etContent = dialogView.findViewById(R.id.et_announcement_content);
        final androidx.appcompat.widget.SwitchCompat switchTop = dialogView.findViewById(R.id.switch_top);
        final TextView tvExpiryDate = dialogView.findViewById(R.id.tv_expiry_date);
        Button btnSelectDate = dialogView.findViewById(R.id.btn_select_date);
        Button btnSubmit = dialogView.findViewById(R.id.btn_submit);
        Button btnCancel = dialogView.findViewById(R.id.btn_cancel);
        
        final String[] expiryDate = {null}; // 用数组存储日期，以便在Lambda表达式中修改
        
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
        builder.setView(dialogView);
        
        final androidx.appcompat.app.AlertDialog dialog = builder.create();
        
        // 设置日期选择按钮点击事件
        btnSelectDate.setOnClickListener(v -> {
            // 获取当前日期
            java.util.Calendar calendar = java.util.Calendar.getInstance();
            int year = calendar.get(java.util.Calendar.YEAR);
            int month = calendar.get(java.util.Calendar.MONTH);
            int day = calendar.get(java.util.Calendar.DAY_OF_MONTH);

            // 创建日期选择器
            android.app.DatePickerDialog datePickerDialog = new android.app.DatePickerDialog(
                    this,
                    (view, selectedYear, selectedMonth, selectedDay) -> {
                        // 格式化日期
                        String date = String.format("%d-%02d-%02d", selectedYear, selectedMonth + 1, selectedDay);
                        tvExpiryDate.setText(date);
                        expiryDate[0] = date;
                    },
                    year, month, day);
            
            // 设置最小日期为明天
            calendar.add(java.util.Calendar.DAY_OF_MONTH, 1);
            datePickerDialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
            
            datePickerDialog.show();
        });
        
        btnSubmit.setOnClickListener(v -> {
            String title = etTitle.getText().toString().trim();
            String content = etContent.getText().toString().trim();
            boolean isTop = switchTop.isChecked();
            
            if (title.isEmpty() || content.isEmpty()) {
                Toast.makeText(AnnouncementActivity.this, "标题和内容不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 创建新公告
            Announcement announcement = new Announcement();
            announcement.setTitle(title);
            announcement.setContent(content);
            announcement.setPublisher("系统管理员");
            announcement.setPublishTime(java.time.LocalDateTime.now().toString());
            announcement.setStatus(Announcement.STATUS_PUBLISHED);
            
            // 设置置顶标志
            announcement.setTop(isTop);
            
            // 设置有效期
            if (expiryDate[0] != null) {
                announcement.setExpiryDate(expiryDate[0]);
            }
            
            // 添加到MockDataManager
            boolean success = MockDataManager.getInstance().addAnnouncement(announcement);
            
            if (success) {
                Toast.makeText(AnnouncementActivity.this, "公告添加成功", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
                loadAnnouncements(); // 重新加载公告列表
            } else {
                Toast.makeText(AnnouncementActivity.this, "公告添加失败", Toast.LENGTH_SHORT).show();
            }
        });
        
        btnCancel.setOnClickListener(v -> dialog.dismiss());
        
        dialog.show();
    }
    
    private void setupNavigationBar() {
        // 获取底部导航视图
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
        
        // 设置当前选中项为"广告"
        bottomNavigationView.setSelectedItemId(R.id.nav_advertisement);
        
        // 设置导航菜单项选择监听器
        bottomNavigationView.setOnItemSelectedListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.nav_home) {
                // 先设置选中项为首页，然后再跳转
                bottomNavigationView.setSelectedItemId(R.id.nav_home);
                startActivity(new Intent(this, MainActivity.class));
                finish();
                return true;
            } else if (itemId == R.id.nav_advertisement) {
                // 当前页面，无需操作
                return true;
            } else if (itemId == R.id.nav_project) {
                // 先设置选中项为项目，然后再跳转
                bottomNavigationView.setSelectedItemId(R.id.nav_project);
                startActivity(new Intent(this, ProjectActivity.class));
                finish();
                return true;
            } else if (itemId == R.id.nav_promotion) {
                // 先设置选中项为推广，然后再跳转
                bottomNavigationView.setSelectedItemId(R.id.nav_promotion);
                startActivity(new Intent(this, PromotionActivity.class));
                finish();
                return true;
            } else if (itemId == R.id.nav_my) {
                // 先设置选中项为我的，然后再跳转
                bottomNavigationView.setSelectedItemId(R.id.nav_my);
                startActivity(new Intent(this, MyActivity.class));
                finish();
                return true;
            }
            return false;
        });
    }
    
    public class AnnouncementAdapter extends RecyclerView.Adapter<AnnouncementAdapter.AnnouncementViewHolder> {
        private Context context;
        private List<Announcement> announcements;
        
        public AnnouncementAdapter(Context context, List<Announcement> announcements) {
            this.context = context;
            this.announcements = announcements;
        }
        
        @NonNull
        @Override
        public AnnouncementViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_announcement_detail, parent, false);
            return new AnnouncementViewHolder(view);
        }
        
        @Override
        public void onBindViewHolder(@NonNull AnnouncementViewHolder holder, int position) {
            Announcement announcement = announcements.get(position);
            
            holder.tvTitle.setText(announcement.getTitle());
            holder.tvContent.setText(announcement.getContent());
            holder.tvPublishTime.setText(formatDateTime(announcement.getPublishTime()));
            holder.tvPublisher.setText(announcement.getPublisher());
            
            // 状态标记
            if (announcement.isDraft()) {
                holder.tvStatus.setText("草稿");
                holder.tvStatus.setBackgroundResource(R.drawable.bg_status_draft);
            } else if (announcement.isPublished()) {
                if (announcement.isTop()) {
                    holder.tvStatus.setText("置顶");
                    holder.tvStatus.setBackgroundResource(R.drawable.bg_status_top);
                } else if (announcement.isExpired()) {
                    holder.tvStatus.setText("已过期");
                    holder.tvStatus.setBackgroundResource(R.drawable.bg_status_expired);
                } else {
                    holder.tvStatus.setText("已发布");
                    holder.tvStatus.setBackgroundResource(R.drawable.bg_status_published);
                }
            } else if (announcement.isArchived()) {
                holder.tvStatus.setText("已归档");
                holder.tvStatus.setBackgroundResource(R.drawable.bg_status_archived);
            }
            
            // 点击查看详情
            holder.itemView.setOnClickListener(v -> {
                showAnnouncementDetail(announcement);
            });
            
            // 管理员可删除和编辑
            if (NetworkUtils.isAdmin()) {
                holder.btnEdit.setVisibility(View.VISIBLE);
                holder.btnDelete.setVisibility(View.VISIBLE);
                
                holder.btnEdit.setOnClickListener(v -> {
                    // 编辑公告
                    showEditAnnouncementDialog(announcement);
                });
                
                holder.btnDelete.setOnClickListener(v -> {
                    // 删除公告
                    confirmDeleteAnnouncement(announcement);
                });
            } else {
                holder.btnEdit.setVisibility(View.GONE);
                holder.btnDelete.setVisibility(View.GONE);
            }
        }
        
        @Override
        public int getItemCount() {
            return announcements.size();
        }
        
        private String formatDateTime(String dateTime) {
            // 简单格式化日期时间
            if (dateTime == null || dateTime.isEmpty()) {
                return "未知时间";
            }
            
            try {
                // 仅显示日期部分
                return dateTime.substring(0, Math.min(10, dateTime.length()));
            } catch (Exception e) {
                return dateTime;
            }
        }
        
        class AnnouncementViewHolder extends RecyclerView.ViewHolder {
            TextView tvTitle;
            TextView tvContent;
            TextView tvPublishTime;
            TextView tvPublisher;
            TextView tvStatus;
            Button btnEdit;
            Button btnDelete;
            
            public AnnouncementViewHolder(@NonNull View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tv_announcement_title);
                tvContent = itemView.findViewById(R.id.tv_announcement_content);
                tvPublishTime = itemView.findViewById(R.id.tv_announcement_date);
                tvPublisher = itemView.findViewById(R.id.tv_publisher);
                tvStatus = itemView.findViewById(R.id.tv_announcement_status);
                btnEdit = itemView.findViewById(R.id.btn_edit);
                btnDelete = itemView.findViewById(R.id.btn_delete);
            }
        }
    }
    
    private void showAnnouncementDetail(Announcement announcement) {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_announcement_detail, null);
        
        TextView tvTitle = dialogView.findViewById(R.id.tv_announcement_title);
        TextView tvContent = dialogView.findViewById(R.id.tv_announcement_content);
        TextView tvPublishTime = dialogView.findViewById(R.id.tv_publish_time);
        TextView tvPublisher = dialogView.findViewById(R.id.tv_publisher);
        
        tvTitle.setText(announcement.getTitle());
        tvContent.setText(announcement.getContent());
        tvPublishTime.setText(formatDateTime(announcement.getPublishTime()));
        tvPublisher.setText(announcement.getPublisher());
        
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
        builder.setView(dialogView);
        builder.setPositiveButton("关闭", null);
        
        builder.create().show();
    }
    
    private void showEditAnnouncementDialog(Announcement announcement) {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_announcement, null);
        
        final com.google.android.material.textfield.TextInputEditText etTitle = dialogView.findViewById(R.id.et_announcement_title);
        final com.google.android.material.textfield.TextInputEditText etContent = dialogView.findViewById(R.id.et_announcement_content);
        final androidx.appcompat.widget.SwitchCompat switchTop = dialogView.findViewById(R.id.switch_top);
        final TextView tvExpiryDate = dialogView.findViewById(R.id.tv_expiry_date);
        Button btnSelectDate = dialogView.findViewById(R.id.btn_select_date);
        Button btnSubmit = dialogView.findViewById(R.id.btn_submit);
        Button btnCancel = dialogView.findViewById(R.id.btn_cancel);
        
        // 设置对话框标题
        TextView dialogTitle = dialogView.findViewById(android.R.id.title);
        if (dialogTitle != null) {
            dialogTitle.setText("编辑公告");
        }
        // 查找顶部标题文本并修改
        TextView headerTitle = null;
        for (int i = 0; i < ((ViewGroup) dialogView).getChildCount(); i++) {
            View child = ((ViewGroup) dialogView).getChildAt(i);
            if (child instanceof TextView && ((TextView) child).getText().toString().equals("添加公告")) {
                headerTitle = (TextView) child;
                break;
            }
        }
        if (headerTitle != null) {
            headerTitle.setText("编辑公告");
        }
        
        // 设置初始值
        etTitle.setText(announcement.getTitle());
        etContent.setText(announcement.getContent());
        switchTop.setChecked(announcement.isTop());
        
        // 设置有效期
        final String[] expiryDate = {announcement.getExpiryDate()};
        if (expiryDate[0] != null && !expiryDate[0].isEmpty()) {
            tvExpiryDate.setText(expiryDate[0]);
        }
        
        // 设置日期选择按钮点击事件
        btnSelectDate.setOnClickListener(v -> {
            // 获取当前日期
            java.util.Calendar calendar = java.util.Calendar.getInstance();
            int year = calendar.get(java.util.Calendar.YEAR);
            int month = calendar.get(java.util.Calendar.MONTH);
            int day = calendar.get(java.util.Calendar.DAY_OF_MONTH);
            
            // 如果已有日期，则解析为初始值
            if (expiryDate[0] != null && !expiryDate[0].isEmpty()) {
                try {
                    java.time.LocalDate date = java.time.LocalDate.parse(expiryDate[0]);
                    year = date.getYear();
                    month = date.getMonthValue() - 1; // 月份从0开始
                    day = date.getDayOfMonth();
                } catch (Exception e) {
                    // 解析失败，使用当前日期
                }
            }

            // 创建日期选择器
            android.app.DatePickerDialog datePickerDialog = new android.app.DatePickerDialog(
                    this,
                    (view, selectedYear, selectedMonth, selectedDay) -> {
                        // 格式化日期
                        String date = String.format("%d-%02d-%02d", selectedYear, selectedMonth + 1, selectedDay);
                        tvExpiryDate.setText(date);
                        expiryDate[0] = date;
                    },
                    year, month, day);
            
            // 设置最小日期为今天
            calendar = java.util.Calendar.getInstance(); // 重置日历为当前日期
            datePickerDialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
            
            datePickerDialog.show();
        });
        
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
        builder.setView(dialogView);
        
        final androidx.appcompat.app.AlertDialog dialog = builder.create();
        
        btnSubmit.setOnClickListener(v -> {
            String title = etTitle.getText().toString().trim();
            String content = etContent.getText().toString().trim();
            boolean isTop = switchTop.isChecked();
            
            if (title.isEmpty() || content.isEmpty()) {
                Toast.makeText(AnnouncementActivity.this, "标题和内容不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 更新公告
            announcement.setTitle(title);
            announcement.setContent(content);
            announcement.setUpdatedAt(java.time.LocalDateTime.now().toString());
            announcement.setTop(isTop);
            
            // 设置有效期
            announcement.setExpiryDate(expiryDate[0]);
            
            // 更新到MockDataManager
            boolean success = MockDataManager.getInstance().updateAnnouncement(announcement);
            
            if (success) {
                Toast.makeText(AnnouncementActivity.this, "公告更新成功", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
                loadAnnouncements(); // 重新加载公告列表
            } else {
                Toast.makeText(AnnouncementActivity.this, "公告更新失败", Toast.LENGTH_SHORT).show();
            }
        });
        
        btnCancel.setOnClickListener(v -> dialog.dismiss());
        
        dialog.show();
    }
    
    private void confirmDeleteAnnouncement(Announcement announcement) {
        new androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("确认删除")
            .setMessage("确定要删除公告 \"" + announcement.getTitle() + "\" 吗？")
            .setPositiveButton("确定", (dialog, which) -> {
                boolean success = MockDataManager.getInstance().deleteAnnouncement(announcement.getId());
                
                if (success) {
                    Toast.makeText(AnnouncementActivity.this, "公告删除成功", Toast.LENGTH_SHORT).show();
                    loadAnnouncements(); // 重新加载公告列表
                } else {
                    Toast.makeText(AnnouncementActivity.this, "公告删除失败", Toast.LENGTH_SHORT).show();
                }
            })
            .setNegativeButton("取消", null)
            .show();
    }
    
    private String formatDateTime(String dateTime) {
        // 简单格式化日期时间
        if (dateTime == null || dateTime.isEmpty()) {
            return "未知时间";
        }
        
        try {
            // 仅显示日期部分
            return dateTime.substring(0, Math.min(10, dateTime.length()));
        } catch (Exception e) {
            return dateTime;
        }
    }
}